package com.government.item.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.government.area.domain.Area;
import com.government.area.mapper.AreaMapper;
import com.government.article.domain.ArticleInformation;
import com.government.article.domain.ArticlePolicy;
import com.government.article.mapper.ArticleInformationMapper;
import com.government.article.mapper.ArticlePolicyMapper;
import com.government.common.core.domain.entity.SysUser;
import com.government.common.exception.ServiceException;
import com.government.common.utils.StringUtils;
import com.government.company.domain.Company;
import com.government.company.mapper.CompanyMapper;
import com.government.item.bo.ItemDataListBO;
import com.government.item.domain.ExcelDetail;
import com.government.item.mapper.ExcelDetailMapper;
import com.government.item.vo.ItemData;
import com.government.item.vo.ItemStatisticsData;
import com.government.tag.domain.Tag;
import com.government.tag.mapper.TagMapper;
import org.apache.commons.compress.utils.Lists;
import org.springframework.transaction.annotation.Transactional;
import com.government.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.government.item.mapper.ExcelListMapper;
import com.government.item.domain.ExcelList;
import com.government.item.service.IExcelListService;

import javax.annotation.Resource;

import static com.government.common.utils.SecurityUtils.getLoginUser;

/**
 * excel记录Service业务层处理
 *
 * @author system
 * @date 2023-09-19
 */
@Service
//@Transactional(rollbackFor = Exception.class)
public class ExcelListServiceImpl implements IExcelListService {
    @Autowired
    private ExcelListMapper excelListMapper;

    @Autowired
    private ExcelDetailMapper excelDetailMapper;

    @Autowired
    private ArticlePolicyMapper articlePolicyMapper;
    @Autowired
    private ArticleInformationMapper articleInformationMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Resource(name = "serviceThreadPool")
    private ExecutorService executorService;

    /**
     * 查询excel记录
     *
     * @param id excel记录主键
     * @return excel记录
     */
    @Override
    public ExcelList selectExcelListById(Long id) {
        return excelListMapper.selectExcelListById(id);
    }

    public static void main(String[] args) {

        System.out.println(Long.parseLong("Mon Nov 20 00:00:00 CST 2023"));
    }

    /**
     * 查询excel记录列表
     *
     * @param excelList excel记录
     * @return excel记录
     */
    @Override
    public List<ExcelList> selectExcelListList(ExcelList excelList) {
        List<ExcelList> excelLists = excelListMapper.selectExcelListList(excelList);
        for (ExcelList item : excelLists) {
            if (StrUtil.isNotBlank(item.getCategory())) {
                String[] categoryIdStrs = item.getCategory().split(",");
                List<Long> categoryIds = Lists.newArrayList();
                for (String categoryId : categoryIdStrs) {
                    categoryIds.add(Long.parseLong(categoryId));
                }

                List<ArticlePolicy> articlePolicyList = articlePolicyMapper.selectList(Wrappers.<ArticlePolicy>lambdaQuery().in(ArticlePolicy::getArticleId, categoryIds));
                if (CollUtil.isNotEmpty(articlePolicyList)) {
                    List<String> categoryNames = articlePolicyList.stream().map(ArticlePolicy::getName).collect(Collectors.toList());
                    item.setCategoryName(String.join(",", categoryNames));
                }
            }
            if (StrUtil.isNotBlank(item.getStatus())) {
                if ("1".equals(item.getStatus())) {
                    item.setStatus("上传完成");
                } else if ("0".equals(item.getStatus())){
                    item.setStatus("上传中");
                } else if ("2".equals(item.getStatus())){
                    item.setStatus("上传终止");
                }
            }
        }

        return excelLists;
    }

    /**
     * 查询excel记录下的立项数据
     *
     * @return excel记录
     */
    @Override
    public List<ExcelDetail> getExcelDetail(Long id) {
        List<ExcelDetail> excelDetailList = excelDetailMapper.selectList(Wrappers.<ExcelDetail>lambdaQuery()
                .eq(ExcelDetail::getEid, id)
                .orderByAsc(ExcelDetail::getSortNo));
        for (ExcelDetail item : excelDetailList) {
            if (StrUtil.isNotBlank(item.getIsApproval())) {
                if ("1".equals(item.getIsApproval())) {
                    item.setIsApproval("是");
                } else {
                    item.setIsApproval("否");
                }
            }
        }

        return excelDetailList;
    }

    /**
     * 新增excel记录
     *
     * @param excelList excel记录
     * @return 结果
     */
    @Override
    public int insertExcelList(ExcelList excelList) {
        excelList.setCreateTime(DateUtils.getNowDate());
        return excelListMapper.insertExcelList(excelList);
    }

    /**
     * 修改excel记录
     *
     * @param excelList excel记录
     * @return 结果
     */
    @Override
    public int updateExcelList(ExcelList excelList) {
        excelList.setUpdateTime(DateUtils.getNowDate());
        return excelListMapper.updateExcelList(excelList);
    }

    /**
     * 批量删除excel记录
     *
     * @param ids 需要删除的excel记录主键
     * @return 结果
     */
    @Override
    public int deleteExcelListByIds(Long[] ids) {
        return excelListMapper.deleteExcelListByIds(ids);
    }

    /**
     * 删除excel记录信息
     *
     * @param id excel记录主键
     * @return 结果
     */
    @Override
    public int deleteExcelListById(Long id) {
        ExcelList excelList = excelListMapper.selectById(id);
//        excelList.setIsDeleted("1");
//        excelList.setUpdateTime(new Date());
//        excelList.setUpdateBy(String.valueOf(getLoginUser().getUserId()));
        excelDetailMapper.delete(Wrappers.<ExcelDetail>lambdaQuery().eq(ExcelDetail::getEid, excelList.getId()));
        return excelListMapper.deleteById(excelList);
    }

    @Override
    public List<ItemData> getItemDataList(Long policyId) {
        ItemDataListBO bo = new ItemDataListBO();
        bo.setPolicyId(policyId);
        List<ItemData> itemDataList = excelDetailMapper.selectItemDataList(bo);
        for (ItemData itemData : itemDataList) {
            StringBuffer address = new StringBuffer();
            if (StrUtil.isNotBlank(itemData.getProvinceName())) {
                address.append(itemData.getProvinceName());
            }
            if (StrUtil.isNotBlank(itemData.getCityName())) {
                address.append("/").append(itemData.getCityName());
            }
            if (StrUtil.isNotBlank(itemData.getDistrictName())) {
                address.append("/").append(itemData.getDistrictName());
            }
            itemData.setAddress(address.toString());
        }
        return itemDataList;
    }

    @Override
    public void importData(String url, List<ExcelDetail> excelDetailList, String policyId, String fileName) {
        SysUser user = getLoginUser().getUser();
        if (StringUtils.isNull(excelDetailList) || excelDetailList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        ArticlePolicy articlePolicy = articlePolicyMapper.selectById(policyId);
        ExcelList excelList = new ExcelList();
        excelList.setName(url);
        excelList.setCategory(policyId);
        excelList.setCategoryName(articlePolicy.getName());
        excelList.setIsDeleted("0");
        excelList.setStatus("0");
        excelList.setCreateTime(new Date());
        excelList.setCreateBy(String.valueOf(user.getUserId()));
        excelList.setFname(fileName);
        excelListMapper.insert(excelList);
        executorService.execute(() -> {

//            List<ExcelList> excelLists = excelListMapper.selectList(Wrappers.<ExcelList>lambdaQuery().eq(ExcelList::getCategory, policyId));
//            if (CollUtil.isNotEmpty(excelLists)) {
//                for (ExcelList item : excelLists) {
//                    excelListMapper.deleteById(item.getId());
//                    excelDetailMapper.delete(Wrappers.<ExcelDetail>lambdaQuery().eq(ExcelDetail::getEid, item.getId()));
//                }
//            }

            try {


            Date lastCompleteTime = null;
            for (ExcelDetail excelDetail : excelDetailList) {
                boolean isApproval = false;
                excelDetail.setCreateBy(String.valueOf(user.getUserId()));
                excelDetail.setCreateTime(new Date());
                excelDetail.setCategory(policyId);
//                String incorporation = excelDetail.getIncorporation();
//                if (incorporation.contains("、")) {
//                    incorporation = incorporation.substring(0, incorporation.indexOf("、"));
//                }
                String sortNumber = excelDetail.getSortNumber().replaceAll(" ", "");
                sortNumber = sortNumber.replaceAll(" ", "");
                excelDetail.setSortNumber(sortNumber);
                String companyNameStr = excelDetail.getIncorporation().replaceAll(" ", "");
                companyNameStr = companyNameStr.replaceAll(" ", "");
                String finalCompanyNameStr1 = companyNameStr + ",";
                String finalCompanyNameStr2 = "," + companyNameStr;
                int count = companyMapper.selectCount(Wrappers.<Company>lambdaQuery()
                        .eq(Company::getName, companyNameStr).or(i -> i.like(Company::getHistoryName, finalCompanyNameStr1)).or(i -> i.like(Company::getHistoryName, finalCompanyNameStr2)));
                if (count > 1) {
                    continue;
                }
                Company company = companyMapper.selectOne(Wrappers.<Company>lambdaQuery()
                        .eq(Company::getName, companyNameStr).or(i -> i.like(Company::getHistoryName, finalCompanyNameStr1)).or(i -> i.like(Company::getHistoryName, finalCompanyNameStr2)));

                excelDetail.setEid(excelList.getId());
                if (StrUtil.isNotBlank(excelDetail.getSource())) {
                    if (excelDetail.getSource().length() > 24) {
                        SimpleDateFormat originalFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
                        SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = null; // 去除开头的"java "
                        try {
                            date = originalFormat.parse(excelDetail.getSource());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        String formattedDate = targetFormat.format(date);
                        Date completeTime = DateUtil.parseDate(formattedDate);
                        excelDetail.setApprovalTime(completeTime);
                        excelDetail.setSource("");
                    } else {
                        // 成文时间最新的资讯
                        ArticleInformation articleInformation = articleInformationMapper.selectOne(Wrappers.<ArticleInformation>lambdaQuery()
                                .select(ArticleInformation::getCompleteTime)
                                .eq(ArticleInformation::getArticleId, Long.parseLong(excelDetail.getSource())));
                        if (Objects.nonNull(articleInformation.getCompleteTime())) {
                            excelDetail.setApprovalTime(articleInformation.getCompleteTime());
                        }
                    }
                }
                if ("是".equals(excelDetail.getIsApproval())) {
                    excelDetail.setIsApproval("1");
                } else {
                    excelDetail.setIsApproval("0");
                }
                if ("是".equals(excelDetail.getInEffect())) {
                    excelDetail.setInEffect("1");
                } else {
                    excelDetail.setInEffect("0");
                }
                if (Objects.nonNull(company)) {
                    excelDetail.setCompanyId(company.getId());
                    excelDetail.setPark1(company.getPark1());
                    excelDetail.setPark2(company.getPark2());
                    excelDetail.setPark3(company.getPark3());
                    excelDetail.setPark4(company.getPark4());
                    excelDetail.setPark5(company.getPark5());
                    excelDetail.setPark6(company.getPark6());
                    excelDetail.setParkName1(company.getParkName1());
                    excelDetail.setParkName2(company.getParkName2());
                    excelDetail.setParkName3(company.getParkName3());
                    excelDetail.setParkName4(company.getParkName4());
                    excelDetail.setParkName5(company.getParkName5());
                    excelDetail.setParkName6(company.getParkName6());
                    excelDetail.setProvince(company.getProvince());
                    excelDetail.setProvinceName(company.getProvinceName());
                    excelDetail.setCity(company.getCity());
                    excelDetail.setCityName(company.getCityName());
                    excelDetail.setDistrict(company.getDistrict());
                    excelDetail.setDistrictName(company.getDistrictName());
                    excelDetail.setNature1(company.getNature1());
                    excelDetail.setNature2(company.getNature2());
                    excelDetail.setNatureName1(company.getNatureName1());
                    excelDetail.setNatureName2(company.getNatureName2());
                    excelDetail.setIndustry1(company.getIndustry1());
                    excelDetail.setIndustry2(company.getIndustry2());
                    excelDetail.setIndustry3(company.getIndustry3());
                    excelDetail.setIndustry4(company.getIndustry4());
                    excelDetail.setIndustryName1(company.getIndustryName1());
                    excelDetail.setIndustryName2(company.getIndustryName2());
                    excelDetail.setIndustryName3(company.getIndustryName3());
                    excelDetail.setIndustryName4(company.getIndustryName4());

                }
                excelDetailMapper.insert(excelDetail);
            }
            } catch (Exception e) {
                excelList.setStatus("2");
                excelListMapper.updateById(excelList);
            }
            excelList.setStatus("1");
            excelListMapper.updateById(excelList);
        });
    }

    @Override
    public List<ItemStatisticsData> getItemStatisticsByAmount(ItemDataListBO bo) {
        List<ItemStatisticsData> result = Lists.newArrayList();

        List<ItemData> itemDataList = excelDetailMapper.selectItemDataList(bo);
        Map<String, List<ItemData>> itemMap = new HashMap<>();
        for (ItemData itemData : itemDataList) {
            if (NumberUtil.isNumber(itemData.getAmount())) {
                if (new BigDecimal(itemData.getAmount()).compareTo(BigDecimal.ZERO) > 0
                        && new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("10")) <= 0) {
                    List<ItemData> itemDataListTemp = itemMap.get("0万<金额<=10万");
                    if (CollUtil.isEmpty(itemDataListTemp)) {
                        itemDataListTemp = new ArrayList<>();
                    }
                    itemDataListTemp.add(itemData);
                    itemMap.put("0万<金额<=10万", itemDataListTemp);
                } else if (new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("10")) > 0
                        && new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("50")) <= 0) {
                    List<ItemData> itemDataListTemp = itemMap.get("10万<金额<=50万");
                    if (CollUtil.isEmpty(itemDataListTemp)) {
                        itemDataListTemp = new ArrayList<>();
                    }
                    itemDataListTemp.add(itemData);
                    itemMap.put("10万<金额<=50万", itemDataListTemp);
                } else if (new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("50")) > 0
                        && new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("100")) <= 0) {
                    List<ItemData> itemDataListTemp = itemMap.get("50万<金额<=100万");
                    if (CollUtil.isEmpty(itemDataListTemp)) {
                        itemDataListTemp = new ArrayList<>();
                    }
                    itemDataListTemp.add(itemData);
                    itemMap.put("50万<金额<=100万", itemDataListTemp);
                } else if (new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("100")) > 0
                        && new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("500")) <= 0) {
                    List<ItemData> itemDataListTemp = itemMap.get("100万<金额<=500万");
                    if (CollUtil.isEmpty(itemDataListTemp)) {
                        itemDataListTemp = new ArrayList<>();
                    }
                    itemDataListTemp.add(itemData);
                    itemMap.put("100万<金额<=500万", itemDataListTemp);
                } else if (new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("500")) > 0
                        && new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("1000")) <= 0) {
                    List<ItemData> itemDataListTemp = itemMap.get("500万<金额<=1000万");
                    if (CollUtil.isEmpty(itemDataListTemp)) {
                        itemDataListTemp = new ArrayList<>();
                    }
                    itemDataListTemp.add(itemData);
                    itemMap.put("500万<金额<=1000万", itemDataListTemp);
                } else if (new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("1000")) > 0) {
                    List<ItemData> itemDataListTemp = itemMap.get("金额>1000万");
                    if (CollUtil.isEmpty(itemDataListTemp)) {
                        itemDataListTemp = new ArrayList<>();
                    }
                    itemDataListTemp.add(itemData);
                    itemMap.put("金额>1000万", itemDataListTemp);
                }
            } else {
                List<ItemData> itemDataListTemp = itemMap.get("金额未统计");
                if (CollUtil.isEmpty(itemDataListTemp)) {
                    itemDataListTemp = new ArrayList<>();
                }
                itemDataListTemp.add(itemData);
                itemMap.put("其他", itemDataListTemp);
            }
        }

        for (Map.Entry<String, List<ItemData>> stringListEntry : itemMap.entrySet()) {
            ItemStatisticsData itemStatisticsData = new ItemStatisticsData();
            itemStatisticsData.setName(stringListEntry.getKey());
            itemStatisticsData.setDataList(stringListEntry.getValue());
            itemStatisticsData.setValue(stringListEntry.getValue().size());
            BigDecimal percent = new BigDecimal(String.valueOf(stringListEntry.getValue().size())).divide(new BigDecimal(String.valueOf(itemDataList.size())), 3, RoundingMode.DOWN);
            itemStatisticsData.setPercent(percent.multiply(new BigDecimal("100")).setScale(1, RoundingMode.DOWN) + "%");
            result.add(itemStatisticsData);
        }
        if (result.size() == 1 && "其他".equals(result.get(0).getName())) {
            result.clear();
        }
        return result;
    }

    @Override
    public List<ItemStatisticsData> getItemStatisticsByArea(ItemDataListBO bo) {
        List<ItemStatisticsData> result = Lists.newArrayList();
        List<Area> areaList = areaMapper.selectList(Wrappers.<Area>lambdaQuery());
        Map<String, Long> areaMap = areaList.stream().collect(Collectors.toMap(Area::getName, Area::getId));
        List<ItemData> itemDataList = excelDetailMapper.selectItemDataList(bo);
        Map<String, List<ItemData>> itemMap = new HashMap<>();
        if (Objects.nonNull(bo.getAreaId())) {
            itemMap = itemDataList.stream().collect(Collectors.groupingBy(ItemData::getDistrictName));
        } else {
            itemMap = itemDataList.stream().collect(Collectors.groupingBy(ItemData::getCityName));
        }
        for (Map.Entry<String, List<ItemData>> stringListEntry : itemMap.entrySet()) {
            ItemStatisticsData itemStatisticsData = new ItemStatisticsData();
            itemStatisticsData.setName(stringListEntry.getKey());
            itemStatisticsData.setDataList(stringListEntry.getValue());
            itemStatisticsData.setValue(stringListEntry.getValue().size());
            if (Objects.isNull(bo.getAreaId())) {
                itemStatisticsData.setId(areaMap.get(itemStatisticsData.getName()));
            }
            BigDecimal percent = new BigDecimal(String.valueOf(stringListEntry.getValue().size())).divide(new BigDecimal(String.valueOf(itemDataList.size())), 3, RoundingMode.DOWN);
            itemStatisticsData.setPercent(percent.multiply(new BigDecimal("100")).setScale(1, RoundingMode.DOWN) + "%");
            result.add(itemStatisticsData);
        }
        return result;
    }

    @Override
    public List<ItemStatisticsData> getItemStatisticsByNature(ItemDataListBO bo) {
        List<ItemStatisticsData> result = Lists.newArrayList();

        // 查询一级性质标签和二级性质标签
        Tag topTag = tagMapper.selectOne(Wrappers.<Tag>lambdaQuery().eq(Tag::getName, "单位类别"));
        List<Tag> allNatureTag = Lists.newArrayList();
        List<Tag> tag1List = tagMapper.selectList(Wrappers.<Tag>lambdaQuery().eq(Tag::getParentId, topTag.getId()));
        allNatureTag.addAll(tag1List);
        for (Tag tag2 : tag1List) {
            List<Tag> tag2List = tagMapper.selectList(Wrappers.<Tag>lambdaQuery().eq(Tag::getParentId, tag2.getId()));
            allNatureTag.addAll(tag2List);
        }

        Map<String, Long> tagMap = allNatureTag.stream().collect(Collectors.toMap(Tag::getName, Tag::getId));

        List<ItemData> itemDataList = excelDetailMapper.selectCompanyItemDataList(bo);

        Map<String, List<ItemData>> itemMap = new HashMap<>();
        if (Objects.nonNull(bo.getNatureId())) {
            itemMap = itemDataList.stream().collect(Collectors.groupingBy(ItemData::getNatureName2));
        } else {
            itemMap = itemDataList.stream().collect(Collectors.groupingBy(ItemData::getNatureName1));
        }
        for (Map.Entry<String, List<ItemData>> stringListEntry : itemMap.entrySet()) {
            ItemStatisticsData itemStatisticsData = new ItemStatisticsData();
            itemStatisticsData.setName(stringListEntry.getKey());
            itemStatisticsData.setDataList(stringListEntry.getValue());
            itemStatisticsData.setValue(stringListEntry.getValue().size());
            if (Objects.isNull(bo.getNatureId())) {
                itemStatisticsData.setId(tagMap.get(itemStatisticsData.getName()));
            }
            BigDecimal percent = new BigDecimal(String.valueOf(stringListEntry.getValue().size())).divide(new BigDecimal(String.valueOf(itemDataList.size())), 3, RoundingMode.DOWN);
            itemStatisticsData.setPercent(percent.multiply(new BigDecimal("100")).setScale(1, RoundingMode.DOWN) + "%");
            result.add(itemStatisticsData);
        }
        return result;
    }

    @Override
    public List<ItemStatisticsData> getItemStatisticsByIndustry(ItemDataListBO bo) {
        List<ItemStatisticsData> result = Lists.newArrayList();

//        List<Industry> industryList = industryMapper.selectList(Wrappers.<Industry>lambdaQuery().eq(Industry::getIsDeleted, "0"));
//        Map<String, Long> tagMap = new HashMap<>();
//        Map<String, Long> tagMap = industryList.stream().collect(Collectors.toMap(Industry::getName, Industry::getId));

        List<ItemData> itemDataList = excelDetailMapper.selectCompanyItemDataList(bo);

        Map<String, List<ItemData>> itemMap = new HashMap<>();
        if (Objects.nonNull(bo.getIndustryId()) && bo.getLevel() == 2) {
            itemMap = itemDataList.stream().collect(Collectors.groupingBy(ItemData::getIndustry2));
        } else if (Objects.nonNull(bo.getIndustryId()) && bo.getLevel() == 3) {
            itemMap = itemDataList.stream().collect(Collectors.groupingBy(ItemData::getIndustry3));
        } else if (Objects.nonNull(bo.getIndustryId()) && bo.getLevel() == 4) {
            itemMap = itemDataList.stream().collect(Collectors.groupingBy(ItemData::getIndustry4));
        } else {
            itemMap = itemDataList.stream().collect(Collectors.groupingBy(ItemData::getIndustry1));
        }
        for (Map.Entry<String, List<ItemData>> stringListEntry : itemMap.entrySet()) {
            ItemStatisticsData itemStatisticsData = new ItemStatisticsData();
            if (Objects.nonNull(bo.getIndustryId()) && bo.getLevel() == 2) {
                itemStatisticsData.setName(stringListEntry.getValue().get(0).getIndustryName2());
            } else if (Objects.nonNull(bo.getIndustryId()) && bo.getLevel() == 3) {
                itemStatisticsData.setName(stringListEntry.getValue().get(0).getIndustryName3());
            } else if (Objects.nonNull(bo.getIndustryId()) && bo.getLevel() == 4) {
                itemStatisticsData.setName(stringListEntry.getValue().get(0).getIndustryName4());
            } else {
                itemStatisticsData.setName(stringListEntry.getValue().get(0).getIndustryName1());
            }
            itemStatisticsData.setDataList(stringListEntry.getValue());
            itemStatisticsData.setValue(stringListEntry.getValue().size());
            if (Objects.isNull(bo.getIndustryId())) {
                itemStatisticsData.setId(Long.parseLong(stringListEntry.getKey()));
            }
            BigDecimal percent = new BigDecimal(String.valueOf(stringListEntry.getValue().size())).divide(new BigDecimal(String.valueOf(itemDataList.size())), 3, RoundingMode.DOWN);
            itemStatisticsData.setPercent(percent.multiply(new BigDecimal("100")).setScale(1, RoundingMode.DOWN) + "%");
            result.add(itemStatisticsData);
        }
        return result;
    }

    @Override
    public List<ItemStatisticsData> getCompanyItemStatisticsByAmount(ItemDataListBO bo) {
        List<ItemStatisticsData> result = Lists.newArrayList();

        List<ItemData> itemDataList = excelDetailMapper.selectCompanyItemDataStatistics(bo);
        Map<String, List<ItemData>> itemMap = new HashMap<>();
        for (ItemData itemData : itemDataList) {
            if (NumberUtil.isNumber(itemData.getAmount())) {
                if (new BigDecimal(itemData.getAmount()).compareTo(BigDecimal.ZERO) > 0
                        && new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("10")) <= 0) {
                    List<ItemData> itemDataListTemp = itemMap.get("0万<金额<=10万");
                    if (CollUtil.isEmpty(itemDataListTemp)) {
                        itemDataListTemp = new ArrayList<>();
                    }
                    itemDataListTemp.add(itemData);
                    itemMap.put("0万<金额<=10万", itemDataListTemp);
                } else if (new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("10")) > 0
                        && new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("50")) <= 0) {
                    List<ItemData> itemDataListTemp = itemMap.get("10万<金额<=50万");
                    if (CollUtil.isEmpty(itemDataListTemp)) {
                        itemDataListTemp = new ArrayList<>();
                    }
                    itemDataListTemp.add(itemData);
                    itemMap.put("10万<金额<=50万", itemDataListTemp);
                } else if (new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("50")) > 0
                        && new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("100")) <= 0) {
                    List<ItemData> itemDataListTemp = itemMap.get("50万<金额<=100万");
                    if (CollUtil.isEmpty(itemDataListTemp)) {
                        itemDataListTemp = new ArrayList<>();
                    }
                    itemDataListTemp.add(itemData);
                    itemMap.put("50万<金额<=100万", itemDataListTemp);
                } else if (new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("100")) > 0
                        && new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("500")) <= 0) {
                    List<ItemData> itemDataListTemp = itemMap.get("100万<金额<=500万");
                    if (CollUtil.isEmpty(itemDataListTemp)) {
                        itemDataListTemp = new ArrayList<>();
                    }
                    itemDataListTemp.add(itemData);
                    itemMap.put("100万<金额<=500万", itemDataListTemp);
                } else if (new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("500")) > 0
                        && new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("1000")) <= 0) {
                    List<ItemData> itemDataListTemp = itemMap.get("500万<金额<=1000万");
                    if (CollUtil.isEmpty(itemDataListTemp)) {
                        itemDataListTemp = new ArrayList<>();
                    }
                    itemDataListTemp.add(itemData);
                    itemMap.put("500万<金额<=1000万", itemDataListTemp);
                } else if (new BigDecimal(itemData.getAmount()).compareTo(new BigDecimal("1000")) > 0) {
                    List<ItemData> itemDataListTemp = itemMap.get("金额>1000万");
                    if (CollUtil.isEmpty(itemDataListTemp)) {
                        itemDataListTemp = new ArrayList<>();
                    }
                    itemDataListTemp.add(itemData);
                    itemMap.put("金额>1000万", itemDataListTemp);
                }
            } else {
                List<ItemData> itemDataListTemp = itemMap.get("金额未统计");
                if (CollUtil.isEmpty(itemDataListTemp)) {
                    itemDataListTemp = new ArrayList<>();
                }
                itemDataListTemp.add(itemData);
                itemMap.put("其他", itemDataListTemp);
            }
        }

        for (Map.Entry<String, List<ItemData>> stringListEntry : itemMap.entrySet()) {
            ItemStatisticsData itemStatisticsData = new ItemStatisticsData();
            itemStatisticsData.setName(stringListEntry.getKey());
            itemStatisticsData.setDataList(stringListEntry.getValue());
            itemStatisticsData.setValue(stringListEntry.getValue().size());
            BigDecimal percent = new BigDecimal(String.valueOf(stringListEntry.getValue().size())).divide(new BigDecimal(String.valueOf(itemDataList.size())), 3, RoundingMode.DOWN);
            itemStatisticsData.setPercent(percent.multiply(new BigDecimal("100")).setScale(1, RoundingMode.DOWN) + "%");
            result.add(itemStatisticsData);
        }
        if (result.size() == 1 && "其他".equals(result.get(0).getName())) {
            result.clear();
        }
        return result;
    }


    @Override
    public List<ItemStatisticsData> getCompanyItemStatisticsByLevel(ItemDataListBO bo) {
        List<ItemStatisticsData> result = Lists.newArrayList();

        List<ItemData> itemDataList = excelDetailMapper.selectCompanyItemDataStatistics(bo);

        Map<String, List<ItemData>> itemMap = new HashMap<>();

        itemMap = itemDataList.stream().filter(item -> StrUtil.isNotBlank(item.getItemGrade())).collect(Collectors.groupingBy(ItemData::getItemGrade));
        for (Map.Entry<String, List<ItemData>> stringListEntry : itemMap.entrySet()) {
            ItemStatisticsData itemStatisticsData = new ItemStatisticsData();
            itemStatisticsData.setName(stringListEntry.getKey());
            itemStatisticsData.setDataList(stringListEntry.getValue());
            itemStatisticsData.setValue(stringListEntry.getValue().size());
            BigDecimal percent = new BigDecimal(String.valueOf(stringListEntry.getValue().size())).divide(new BigDecimal(String.valueOf(itemDataList.size())), 3, RoundingMode.DOWN);
            itemStatisticsData.setPercent(percent.multiply(new BigDecimal("100")).setScale(1, RoundingMode.DOWN) + "%");
            result.add(itemStatisticsData);
        }
        return result;
    }

    @Override
    public List<ItemStatisticsData> getCompanyItemStatisticsByOrg(ItemDataListBO bo) {
        List<ItemStatisticsData> result = Lists.newArrayList();

        List<ItemData> itemDataList = excelDetailMapper.selectCompanyItemDataStatistics(bo);

        Map<String, List<ItemData>> itemMap = new HashMap<>();

        itemMap = itemDataList.stream().collect(Collectors.groupingBy(ItemData::getOrgName));
        for (Map.Entry<String, List<ItemData>> stringListEntry : itemMap.entrySet()) {
            ItemStatisticsData itemStatisticsData = new ItemStatisticsData();
            itemStatisticsData.setName(stringListEntry.getKey());
            itemStatisticsData.setDataList(stringListEntry.getValue());
            itemStatisticsData.setValue(stringListEntry.getValue().size());
            BigDecimal percent = new BigDecimal(String.valueOf(stringListEntry.getValue().size())).divide(new BigDecimal(String.valueOf(itemDataList.size())), 3, RoundingMode.DOWN);
            itemStatisticsData.setPercent(percent.multiply(new BigDecimal("100")).setScale(1, RoundingMode.DOWN) + "%");
            result.add(itemStatisticsData);
        }
        return result;
    }

    @Override
    public List<ItemStatisticsData> getCompanyItemStatisticsByYear(ItemDataListBO bo) {
        List<ItemStatisticsData> result = Lists.newArrayList();

        List<ItemData> itemDataList = excelDetailMapper.selectCompanyItemDataStatistics(bo);

        Map<String, List<ItemData>> itemMap = new HashMap<>();

        itemMap = itemDataList.stream().collect(Collectors.groupingBy(ItemData::getYear));
        for (Map.Entry<String, List<ItemData>> stringListEntry : itemMap.entrySet()) {
            ItemStatisticsData itemStatisticsData = new ItemStatisticsData();
            itemStatisticsData.setName(stringListEntry.getKey());
            itemStatisticsData.setDataList(stringListEntry.getValue());
            itemStatisticsData.setValue(stringListEntry.getValue().size());
            BigDecimal percent = new BigDecimal(String.valueOf(stringListEntry.getValue().size())).divide(new BigDecimal(String.valueOf(itemDataList.size())), 3, RoundingMode.DOWN);
            itemStatisticsData.setPercent(percent.multiply(new BigDecimal("100")).setScale(1, RoundingMode.DOWN) + "%");
            result.add(itemStatisticsData);
        }
        return result;
    }

    @Override
    public String getCompanyItemStatistics(ItemDataListBO bo) {

        List<ItemData> itemDataList = excelDetailMapper.selectCompanyItemDataStatistics(bo);

        Map<String, List<ItemData>> itemMap = new HashMap<>();

        int total = itemDataList.size();

        List<ItemData> specialFundList = itemDataList.stream().filter(item -> "1".equals(item.getItemType())).collect(Collectors.toList());

        int specialFundTotal = specialFundList.size();

        List<ItemData> honorList = itemDataList.stream().filter(item -> "2".equals(item.getItemType())).collect(Collectors.toList());

        int honorTotal = honorList.size();

        BigDecimal totalAmount = BigDecimal.ZERO;
        List<ItemData> itemDataAmountList = itemDataList.stream().filter(item -> NumberUtil.isNumber(item.getAmount())).collect(Collectors.toList());
        for (ItemData itemData : itemDataAmountList) {
            totalAmount = totalAmount.add(new BigDecimal(itemData.getAmount()));
        }

        return "根据平台立项数据库查询显示，公司共有" + total + "条立项信息，其中：专项资金" + specialFundTotal + "项，荣誉资质" + honorTotal + "项，各类奖补、资助总金额" + totalAmount + "万（如有偏差，敬请谅解）";
    }

    @Override
    public void failDataHandler() {
        List<ExcelDetail> itemDataList = excelDetailMapper.selectList(Wrappers.<ExcelDetail>lambdaQuery()
                .select(ExcelDetail::getIncorporation)
                .eq(ExcelDetail::getCompanyId, 0L).likeLeft(ExcelDetail::getIncorporation, "有限公司").groupBy(ExcelDetail::getIncorporation));
        if (CollUtil.isNotEmpty(itemDataList)) {
            for (ExcelDetail excelDetail : itemDataList) {
                String finalCompanyNameStr1 = excelDetail.getIncorporation() + ",";
                String finalCompanyNameStr2 = "," + excelDetail.getIncorporation();
                int count = companyMapper.selectCount(Wrappers.<Company>lambdaQuery()
                        .eq(Company::getName, excelDetail.getIncorporation()).or(i -> i.like(Company::getHistoryName, finalCompanyNameStr1)).or(i -> i.like(Company::getHistoryName, finalCompanyNameStr2)));
                if (count==0 || count > 1) {
                    continue;
                }
                Company company = companyMapper.selectOne(Wrappers.<Company>lambdaQuery().select(Company::getId)
                        .eq(Company::getName, excelDetail.getIncorporation()).or(i -> i.like(Company::getHistoryName, finalCompanyNameStr1)).or(i -> i.like(Company::getHistoryName, finalCompanyNameStr2)));
                if (Objects.nonNull(company)) {
                    excelDetailMapper.updateExcelDetailByCompany(excelDetail.getIncorporation(), company.getId());
                }
            }
        }
    }

}
